<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-col>
          <el-alert title="警告提示的文案" type="warning" show-icon></el-alert>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- options是数据源  -->
          <el-cascader
            v-model="selectKey"
            :options="cateList"
            :props="cascaderProps"
            @change="cateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- many 静态参数 -->
        <el-tab-pane label="静态参数" name="many">
          <el-button
            type="primary"
            size="small"
            :disabled="isButDisabled"
            @click="addParamsDialogVisible=true"
          >静态参数</el-button>
          <el-table :data="manyList" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag -->
                <el-tag
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  @close="removeAttr(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- only 动态属性 -->
        <el-tab-pane label="动态属性" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="isButDisabled"
            @click="addParamsDialogVisible=true"
          >动态属性</el-button>
          <el-table :data="onlyList" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag -->
                <el-tag
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  @close="removeAttr(index,scope.row)"
                >{{item}}</el-tag>
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditParams(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDailogClose"
    >
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules">
        <el-form-item :label="titleText" prop="attr_name" :label-width="formLabelWidth">
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDailogClose">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      :title="'编辑'+titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDailogClose"
    >
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item :label="titleText" prop="attr_name" :label-width="formLabelWidth">
          <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDailogClose">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 存储数据列表
      cateList: [],
      formLabelWidth: '120px',
      // 多级列表中的参数
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 只能选择最后一级,
        emitPath: 'false'
      },
      selectKey: [],
      // tab标签默认选中
      activeName: 'many',
      manyList: [],
      onlyList: [],
      addParamsDialogVisible: false,
      editParamsDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_id: '',
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 2, max: 60, message: '长度在 2 到 60 个字符', trigger: 'blur' }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 2, max: 60, message: '长度在 2 到 60 个字符', trigger: 'blur' }
        ]
      },
      // input输入框的显示
      inputVisible: false,
      inputValue: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败！')
      // this.$message.success(res.meta.msg)
      this.cateList = res.data
    },
    // 属性获取数据
    async getParamsData () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败！')
      // 在赋值前将data.attr_vals字符串转成数组
      // 若有数据不为空就转换为数组，否则为空数组
      res.data.forEach(element => {
        element.attr_vals =
          element.attr_vals ? element.attr_vals.split(',') : []
        // 给这个data数组添加2个自定义的属性值
        element.inputVisible = false
        element.inputValue = ''
      })
      // console.log(res.data)
      // 转换后赋值给对应的数组
      if (this.activeName === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
    },
    // 级联选择器变化后触发
    cateChange () {
      // console.log(this.selectKey)
      // console.log(this.cateId)
      this.getParamsData()
    },
    // tab切换触发
    handleTabClick () {
      // console.log(this.activeName)
      this.getParamsData()
    },
    // 添加属性方法
    addParams () {
      // console.log('------------------')
      // console.log(this.cateId)
      // console.log(this.addForm.attr_name)
      // console.log(this.activeName)
      // console.log('------------------')
      this.$refs.addFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    // 添加属性对话框关闭时触发
    addParamsDailogClose () {
      this.$refs.addFormRef.resetFields()
      this.addParamsDialogVisible = false
    },
    async showEditParams (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('查询参数失败！')
      this.editForm = res.data
      this.editParamsDialogVisible = true
    },
    editParams () {
      this.$refs.editFormRef.validate(async validate => {
        if (!validate) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('添加参数失败！')
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    // 添加属性对话框关闭时触发
    editParamsDailogClose () {
      this.$refs.editFormRef.resetFields()
      this.editParamsDialogVisible = false
    },
    // 提交数据函数，方便多次调用
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          // 我们的数据是数组，后端要求是字符串，通过join方法转换为字符串
          attr_vals: row.attr_vals.join(',')
        })

      if (res.meta.status !== 200) return this.$message.error('添加参数失败')
      this.$message.success(res.meta.msg)

      // 提交后清空数据，否则失去焦点和回车都会触发事件，不清空就提交了2次数据
      row.inputValue = ''
      row.inputVisible = false
    },
    // 根据attr id删除参数
    async removeParams (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败')
      }
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 若输入了值就存入数组中，并提交到后台
      row.attr_vals.push(row.inputValue.trim())
      // row.inputValue = ''
      // row.inputVisible = false
      // console.log(row.inputValue.trim())
      // console.log(row.attr_sel)
      // console.log(row.attr_vals.join(' '))
      this.saveAttrVals(row)
    },
    showInput (row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      // $nextTick 当页面重新渲染后执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除单个属性值
    removeAttr (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    isButDisabled () {
      if (this.selectKey.length === 0) {
        return true
      }
      return false
    },
    cateId () {
      return this.selectKey.slice(-1).join()
    },
    titleText () {
      if (this.activeName === 'many') {
        return '静态参数'
      }
      return '动态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.input-new-tag {
  width: 150px;
}
</style>
